package org.balabala.user.controller;

import java.util.*;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sf.jsqlparser.statement.select.First;
import org.balabala.user.entity.UserEntity;
import org.balabala.user.service.UserService;
import org.balabala.user.utils.PageUtils;
import org.balabala.user.utils.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.crypto.Data;


/**
 * 
 *
 * @author hanshanxi
 * @email 3176988793@qq.com
 * @date 2021-09-04 09:31:52
 */
@RestController
@RequestMapping("/balabala/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public Resp list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);
        return Resp.ok().put("data", page);
    }

    //TODO
    /**
     * 模糊查询
     */
    @RequestMapping("/list/keyword")
    public Resp list(@RequestParam Integer page, @RequestParam Integer limit,@RequestParam String key,@RequestParam Integer state){
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("keyword",key);
        hashMap.put("page",page.toString());
        hashMap.put("limit",limit.toString());
        hashMap.put("state",state);
        PageUtils pageUtils =  userService.selectByKeyword(hashMap);
        return Resp.ok().put("data",pageUtils);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{uid}")

    public Resp infoByUid(@PathVariable("id") Long uid){
		UserEntity user = userService.selectByUid(uid);
        if(user.getState() == 1){
            return Resp.error(500,"该用户已被封禁");
        }else {
            return Resp.ok().put("data", user);
        }

    }

    @RequestMapping("/info/uid")
    public Resp info(@RequestBody Long uid){
        UserEntity user = userService.selectByUid(uid);
        if(user == null){
            return  Resp.error(500,"用户不存在");
        }else if(user.getState() == 1) {
            return Resp.error(500,"该用户已被封禁");
        }else {
            return Resp.ok().put("data", user);
        }
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public Resp save(@RequestBody UserEntity user){
		userService.save(user);
        return Resp.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Resp update(@RequestBody UserEntity user){
        //更新用户信息
        boolean bool = userService.update(user,new QueryWrapper<UserEntity>().eq("uid",user.getUid()));
        if(bool){
            //更新成功进行回显
            UserEntity userEntity = userService.selectByUid(user.getUid());
            if(userEntity == null){
                return Resp.error(500,"回显失败");
            }else {
                userEntity.setPassword(null);
                return Resp.ok().put("data",userEntity);
            }
        }else{
            return Resp.error(500,"更新失败");
        }
    }
    /**
     * 封禁用户信息
     */
    @RequestMapping("/banuser")
    public  Resp ban(@RequestBody UserEntity user){
        user.setState(1);
        boolean uid = userService.update(user, new QueryWrapper<UserEntity>().eq("uid", user.getUid()));
        if(uid){
            return Resp.ok();
        }else {
            return Resp.error(500,"封禁失败");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/batchdelete")
    public Resp delete(@RequestBody  HashMap<String,Object> hashMap){
        Object object = hashMap.get("ids");
        Long[] ids = JSON.parseObject(JSON.toJSONString(object), new TypeReference<Long[]>() {
        });

        Integer state = (Integer)hashMap.get("state");
        boolean b = userService.banByIds(ids,state);
        if(b){
            return Resp.ok();
        }else {
            return Resp.error(500,"删除失败");
        }
    }

    /**
     * 验证用户信息
     * @param userEntity 包含用户信息的实体类
     * @return
     */
    @PostMapping("/login")
    public Resp login(@RequestBody UserEntity userEntity){
        return userService.login(userEntity);
    }

    /**
     * 注册
     *
     */
    @PostMapping("/register")
    public Resp register(@Valid @RequestBody UserEntity userEntity,BindingResult result){
        //对传入的数值进行校验
        Map<String,String> error = new HashMap<String,String>();
        if(result.hasErrors()){
            //如果有报错信息，将报错信息保存到map中进行返回
            result.getFieldErrors().forEach(item -> {
                error.put(item.getField(),item.getDefaultMessage());
                System.out.println("error"+item.getField()+":"+item.getDefaultMessage());
            });
            //将错误信息返回
            return Resp.error(500,"注册信息格式不正确").put("data",error);
        }else {
            return userService.register(userEntity);
        }
    }

    /**
     * 实现用户的批量查询
     */
    @PostMapping("/listByUids")
    public Resp selectListByUids(@RequestBody List<Long> ids)
    {
        List<UserEntity> lists =  userService.selectListByUids(ids);
        if(lists == null){
            return Resp.error(500,"查询失败");
        }else{
            return  Resp.ok().put("data",lists);
        }
    }


}
